<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索区 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="params.query"
            clearable
            @clear="getUserdata"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserdata"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表单区 -->
      <el-table :data="UserLists" border style="width: 100%" stripe>
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="role_name" label="权限" width="180"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="editFormHandle(scope.row.id)"
            ></el-button>
            <el-button type="danger" icon="el-icon-delete" circle @click="deleteForm(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="点我啊" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" circle @click="setRights(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pagenum"
        :page-sizes="[params.pagesize, 4, 6, 8]"
        :page-size="params.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户弹框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%" @close="resetAddForm">
      <!-- 弹框主题 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" tyoe="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 弹框按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFormHandle">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户弹框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="30%" @close="resetEditForm">
      <!-- 弹框主题 -->
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 弹框按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="putForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配用户弹框 -->
    <el-dialog title="分配用户权限" :visible.sync="setDialogVisible" width="30%">
      <!-- 弹框主题 -->
      <p>{{ userInfo.username }}</p>
      <p>{{ userInfo.role_name }}</p>
      <p>
        分配角色：
        <el-select v-model="userID" placeholder="请选择">
          <el-option
            v-for="item in userData"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <!-- 弹框按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setHandle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证手机号
    const CheckMobile = (rule, val, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(val)) {
        return callback()
      }
      callback(new Error('请输入正确手机号'))
    }

    // 验证邮箱
    const CheckEmail = (rule, val, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(val)) {
        return callback()
      }
      callback(new Error('请输入正确邮箱'))
    }

    return {
      // 用户id数据
      userID: '',
      userData: [],
      userInfo: {},
      setDialogVisible: false, // 控制分配权限弹框的显示隐藏
      count: 20555,
      // 编辑用户弹框表单信息
      editForm: {},
      // 添加用户弹框表单信息
      addForm: {
        username: '10000',
        password: '199522',
        email: '999@qq.com',
        mobile: '18300000000'
      },
      addFormRules: {
        // 用户名校验
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        // 密码校验
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码错误', trigger: 'blur' }
        ],
        // 对邮箱进行校验
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: CheckEmail, trigger: 'blur' }
        ],
        // 对手机号进行校验
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: CheckMobile, trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      editDialogVisible: false,
      params: {
        query: '',
        pagenum: 1,
        pagesize: 8
      },
      total: 0,
      UserLists: []
    }
  },
  created() {
    this.getUserdata()
  },
  methods: {
    async getUserdata() {
      const { data: res } = await this.$http.get('users', { params: this.params })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.UserLists = res.data.users
      this.total = res.data.total
      //   console.log(res)
    },

    // 改变用户状态
    async changeState(states) {
      const { data: res } = await this.$http.put(`users/${states.id}/state/${states.mg_state}`)
      if (res.meta.status !== 200) {
        states.mg_state = !states.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },

    // 每页显示条数改变时触发
    handleSizeChange(pagesize) {
      this.params.pagesize = pagesize
      this.getUserdata()
    },

    // 页码改变是触发
    handleCurrentChange(pagenum) {
      this.params.pagenum = pagenum
      this.getUserdata()
    },

    // 重置添加用户表单
    resetAddForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 重置编辑表单
    resetEditForm() {
      this.$refs.editFormRef.resetFields()
    },

    // 添加用户
    addFormHandle() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 关闭弹框
        this.dialogVisible = false
        // 刷新页面
        this.getUserdata()
      })
      setTimeout(() => {
        this.count += 1
      }, 300)
    },

    // 编辑用户
    async editFormHandle(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editForm = res.data
      this.editDialogVisible = true
    },

    // 更新用户信息
    async putForm() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editDialogVisible = false
        this.getUserdata()
      })
    },

    // 删除用户
    deleteForm(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('users/' + id)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.getUserdata()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    //
    async setRights(params) {
      this.userInfo = params
      console.log(params)
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userData = res.data
      this.setDialogVisible = true
    },

    // 分配权限
    async setHandle() {
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.userID
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.setDialogVisible = false
      this.getUserdata()
    }
  }
  // 监听函数
  // watch: {
  //   count(val) {
  //     // setTimeout(() => {
  //     this.addFormHandle()
  //     this.addForm.username = val + ''
  //     // }, 1000)
  //   }
  // }
}
</script>

<style lang="less" scoped>
</style>
